#!/usr/bin/env python
# encoding: utf-8
# @author: Lin Han
# @contact: voldemort22@126.com
# @file: kill_and_restart.py
# @time: 2021/6/3 14:50
# @desc:
import docker

client = docker.from_env()

# container = client.containers.run("redis", detach=True, command="redis-server", ports={"6379/tcp": 6379})
#
# for i in client.containers.list():
#     print(i.name)
#     print(i.ports)
#     # print(dir(i))
#
#     temp_container = client.containers.get(i.name)
#     temp_container.stop()
#     temp_container.remove()


def kill_container(container: docker.models.containers.Container):
    """
    停止并杀死输入的容器。
    :param container:
    """
    try:
        container.stop()
    except:
        pass
    try:
        container.remove()
    except:
        pass


def restart_container(name: str, port: int):
    """
    重启输入的容器。
    传入前不必判断容器是否存在。
    :param container:
    """
    client = docker.from_env()
    try:
        container = client.containers.get(name)
        kill_container(container)
    except:
        pass

    client.containers.run("redis", detach=True, name=name, command="redis-server", ports={"6379/tcp": port})


# if __name__ == '__main__':
#     restart_container(name="history_clamp", port=10001)